#!/bin/bash
#
#  xapi        Startup script for xapi toolstack
#
# chkconfig: 2345 13 88
# description: Manages VMs and resource pools
### BEGIN INIT INFO
# Provides: xapi
# Required-Start: $local_fs $network $syslog xcp-rrdd message-switch
# Required-Stop: $local_fs $syslog
# Should-Start: $syslog message-switch
# Should-Stop: $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: xapi toolstack
# Description:       Manages VMs and resource pools
### END INIT INFO

# Source function library.
. /lib/lsb/init-functions

RETVAL=0
PIDFILE=/var/run/xapi.pid

prog=xapi
exec=/usr/sbin/xapi
if [ -d /var/lock/subsys ] ; then
    lockfile=/var/lock/subsys/$prog
else
    lockfile=/var/lock/$prog
fi

# Source config
if [ -f /etc/sysconfig/$prog ] ; then
    . /etc/sysconfig/$prog
fi

# Use 'blktap 2.5' if it has been installed
if [ -d /usr/lib64/blktap ]; then
        export XCP_PATH=/usr/lib64/blktap/sbin
        export TAPDISK2=/usr/lib64/blktap/libexec/tapdisk
elif [ -d /usr/lib/blktap ]; then
        export XCP_PATH=/usr/lib/blktap/sbin
        export TAPDISK2=/usr/lib/blktap/libexec/tapdisk
fi
logger -t ffs "XCP_PATH=${XCP_PATH} TAPDISK2=${TAPDISK2}"


start() {
	[ -x $exec ] || exit 5

	umask 077

        echo -n $"Starting xapi: "
        export OCAMLRUNPARAM=b
        start_daemon -p "$PIDFILE" $exec -pidfile "$PIDFILE" -daemon true $XAPI_OPTIONS
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch $lockfile
        return $RETVAL
}
stop() {
        echo -n $"Shutting down xapi: "

        # Use the CLI to request a clean shutdown
        RETRIES=60
        while [ ${RETRIES} -ne 0 ]; do
                xe host-shutdown-agent 2> /dev/null
                # Finish if all xapis have gone 
                xapi_pids=$(pidof $prog)
                if [ -z "$xapi_pids" ]; then
                        logger "xapi stopped successfully"
                        rm -f $PIDFILE $lockfile
                        success $"xapi stopped successfully"
                        echo
                        return 0
                fi
                sleep 1
                echo -n .
                RETRIES=$(( ${RETRIES} - 1 ))
        done

        killproc -p "$PIDFILE" $exec
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && rm -f $lockfile
        return $RETVAL
}
rhstatus() {
        status_of_proc -p "$PIDFILE" $exec $prog
}
restart() {
        stop
        start
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  reload)
        exit 3
        ;;
  force-reload)
        restart
        ;;
  status)
        rhstatus
        ;;
  condrestart|try-restart)
        rhstatus >/dev/null 2>&1 || exit 0
        restart
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|condrestart|try-restart|reload|force-reload|status}"
        exit 3
esac

exit $?
